import { RootThunkAction } from '@/types/store'
import { http } from '@/utils/http'
import { clearToken, setToken } from '@/utils/token'
// import type { Token } from '@/types/data'
import type { LoginResponse } from '@/types/data'

// 请求数据的约束
type LoginParams = { mobile: string; code: string }

// 登录请求返回的数据类型约束
// type LoginResponse = {
//   message: string
//   data: Token
// }

// 异步请求action，发一个异步请求，发同步action
export const login = (data: LoginParams): RootThunkAction => {
  return async dispatch => {
    // 发起异步登录请求
    const res = await http.post<LoginResponse>('/authorizations', data)
    console.log('登录返回数据', res)
    const token = res.data.data

    // 保存到本地
    setToken(token)

    // dispatch 同步action
    dispatch({
      type: 'login/token',
      payload: token
    })
  }
}
export const getCode = (mobile: string): RootThunkAction => {
  return async dispatch => {
    await http.get(`/sms/codes/${mobile}`)
  }
}
// 退出登录action
export const logout = (): RootThunkAction => {
  return dispatch => {
    // 清空本地token
    clearToken()

    // 清空redux
    dispatch({
      type: 'login/token',
      payload: { token: '', refresh_token: '' }
    })
  }
}
